<template>
  <el-dialog title="密码修改" :visible.sync="dialogFormVisible" @close="resetForm">
    <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="120px">
      <el-form-item label="账号" prop="userName">
        <el-input v-model="editForm.username" style="width: 260px" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="editForm.oldPassword" placeholder="请输入原密码" show-password style="width: 260px"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="editForm.newPassword" placeholder="请输入新密码" show-password style="width: 260px"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="resetForm">取 消</el-button>
      <el-button type="primary" @click="confirmEdit" :loading="editLoading">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import api from '../api/index.js';
export default {
  props: {},
  computed: {
    userInfo() {
      return this.$store.getters.userInfo;
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      editForm: {
        username: '',
        oldPassword: '',
        newPassword: '',
      },
      editLoading: false,
      editRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
        ],
      },
    }
  },
  watch: {},
  created() {
  },
  mounted() { },
  methods: {
    open() {
      this.dialogFormVisible = true;
      this.editForm.username = this.userInfo.userName;
    },
    confirmEdit() {
      if (this.editForm.oldPassword === this.editForm.newPassword) {
        this.$message.warning("新密码不可以与原密码一致");
        return;
      }
      this.$refs['editForm'].validate((result) => {
        if (result) {
          this.editLoading = true;
          api.updatePassword({
            oldPassword: this.$utils.encrypt(this.editForm.oldPassword),
            newPassword: this.$utils.encrypt(this.editForm.newPassword),
          })
            .then((res) => {
              this.editLoading = false;
              if (res.success) {
                this.dialogFormVisible = false;
                this.$refs['editForm'].resetFields();
                this.$emit('success');
              } else {
                this.$message.error('修改用户密码失败：' + (res.message || ''));
              }
            })
            .catch((e) => {
              this.editLoading = false;
              this.$log.error('修改用户密码失败，错误信息为：', e);
            });
        }
      });
    },
    resetForm() {
      this.$refs['editForm'].resetFields();
      this.dialogFormVisible = false;
    },
  }
}
</script>
<style lang="scss" scoped></style>